<template>
  <div> 
    <el-table
      ref="materialTable"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="data"
      :border="border"
      @selection-change="handleSelectionChange">

      <el-table-column v-if="!canSelectMaterial" type="selection" align="center" width="48"></el-table-column>

      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :width="column.width"
        :min-width="column.minWidth"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">

          <!-- start 物料名称 -->
          <template v-if="column.fieldName === 'materialName'">
            <template v-if="canSelectMaterial">
              <biz-remote-select
                :placeholder="$t('common.placeholder.select')"
                :value="[scope.row]"
                :remote-method="fetchMaterial"
                @input="chooseMaterial($event, scope.row, scope.$index)"
              >
                <div class="search-in-part-item" slot="option" slot-scope="{ option }">
                  <template v-if="option.materialName && !loading">
                    <p>{{$t('common.form.preview.materialReturn.tableLabel1')}}：<span>{{ option.materialName }}</span></p>
                    <p>{{$t('common.form.preview.materialReturn.colum1')}}：<span>{{ option.materialSn }}</span></p>
                    <p>{{$t('common.form.preview.materialReturn.tableLabel4')}}：<span>{{ option.materialProperty }}</span></p>
                  </template>
                  <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
                </div>
              </biz-remote-select>
            </template>
            <template v-else>
              {{scope.row[column.fieldName]}}
            </template>
          </template>
          <!-- end 物料名称 -->

          <!-- start 申请数量 -->
          <template v-else-if="column.fieldName === 'number'">
            <el-input-number v-model="scope.row.number" step-strictly controls-position="right" :min="1" :max="scope.row.availableNum">
            </el-input-number>
          </template>
          <!-- end 申请数量 -->

          <template v-else-if="column.fieldName === 'materialProperty'">
            {{scope.row.materialProperty || scope.row.property}}
          </template>

          <template v-else-if="column.fieldName === 'materialUnit'">
            {{scope.row.materialUnit || scope.row.unit}}
          </template>

          <template v-else-if="column.fieldName === 'isSnManageDict'">
            {{scope.row.isSnManageDict || scope.row.snManage}}
          </template>

          <template v-else-if="column.fieldName === 'positionName'">
            {{scope.row.positionName || scope.row.warehousePositionName}}
          </template>

          <template v-else-if="column.fieldName === 'SN'">
            <!-- TODO 国际化待办 -->
            <el-button 
              v-if="scope.row.isSnManageDict === '是' || scope.row.snManage === '是'"
              class="text-danger" type="text" size="mini" 
              @click="openSnDialog('add', scope.row, scope.$index)">

              ({{scope.row.snList.length || 0}}/{{scope.row.number}}){{$t('common.base.add2')}}

            </el-button>
          </template>

          <!-- start 操作 -->
          <template v-else-if="column.fieldName === 'action'">
            <el-button class="text-danger" type="text" size="mini" @click="data.splice(scope.$index, 1)">{{$t('common.base.delete')}}</el-button>
          </template>
          <!-- end 操作 -->

          <template v-else>{{ scope.row[column.fieldName] }}</template>
        </template>
      </el-table-column>
    </el-table>

    <!-- start sn弹窗 -->
    <material-sn-dialog 
      ref="materialSnDialog" 
      :data="data" 
      @changeSn="changeSn"
    />
    <!-- end sn弹窗 -->
  </div>
</template>

<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* util */
import MathUtil from '@src/util/math';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
/* component */
import SearchMaterialSelect from '@src/component/form/common/warehouse/SearchMaterialSelect.vue';
import MaterialSnDialog from './MaterialSnDialog';

export default {
  name: 'material-table',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    border: {
      type: Boolean,
      default: false
    },
    // 可选择物料
    canSelectMaterial: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    card: {
      type: Object,
      default: () => ({})
    },
    waregouseType: {
      type: String,
      default: ''
    },
    warehouseId: [String, Number], // 仓库id，查询物料库存用
    positionId: [String, Number] // 仓位id，查询物料库存用
  },
  inject: ['initData'],
  data() {
    return {
      emptyData: {
        materialSn: '',
        salePrice: 0,
        number: 1,
        materialName: '',
        sort: '',
        materialUnit: '',
        id: '',
        relationStandard: '',
        snList: [],
        materialProperty: '',
        isSnManageDict: '',
        warehouseId: '',
        warehouseName: '',
        positionId: '',
        positionName: '',
        num: 0, // 总库存
        materialId: '',
        availableNum: 0, // 库存数量
        warrantyStatus: ''
      },
      loading: false,
      multipleSelection: []
    }
  },
  computed: {
    showRepertory() {
      let idx = this.colums.findIndex(item => item.fieldName == 'repertory')
      return idx > -1;
    }
  },
  methods: {
    openSnDialog(type, row, index) {
      let isMaterialApply = false
      if(row.isOutWarehouse) {
        isMaterialApply = true
      }
      this.$refs.materialSnDialog.open(type, row, index, isMaterialApply)
    },
    changeSn(data) {
      this.data = data
    },
    /**
     * @description 添加一条表格数据
    */
    add() {
      if (this.data.length > 19) {
        return this.$message({
          showClose: true,
          message: this.$t('common.form.preview.materialVerifyEliminate.addMaterialMax', {max: 20}),
          type: 'error'
        })
      }

      this.data.push({...this.emptyData});
    },
    /**
     * @description 搜索物料
    */
    async fetchMaterial(params) {
      try {
        this.loading = true;
        const { keyword, pageNum, pageSize } = params
        // 查库存
        let fn = 'getInventoryList'
        let isParams = {
          keyword,
          pageNum,
          pageSize,
          positionId: this.positionId,
          warehouseId: this.warehouseId
        }
        // 查个人库存
        if(this.waregouseType === 'personalLibrary') {
          fn = 'getPersonalInventoryList'
          isParams = {
            keyword,
            isPersonal: true,
            pageNum,
            pageSize,
            positionId: this.positionId,
            warehouseId: this.warehouseId
          }
        }
        let res = await WareHouseApi[fn](isParams);
        this.loading = false;
        if (!res.success) return;
        res.data.list = res.data.list.map(item => {
          return {
            label: item.materialName,
            value: item.id,
            ...item,
          }
        });

        return res.data;
      } catch (error) {
        this.loading = false;
        console.warn('fetchMaterial -> error', error);
      } 
    },
    /**
     * @description 选择物料
    */
    chooseMaterial(value, row, index) {
      let newRow = row;
      let selectedMaterial = value?.[0] || {};
      if(!selectedMaterial.id) return;
      
      // 判断当前选择的物料是否已经存在, 排除本身
      let idx = this.data.findIndex(item => item.id == selectedMaterial.id);
      if(idx > -1 && idx != index) return this.$platform.toast(this.$t('common.form.preview.materialVerifyEliminate.tip2'), 'warning');

      Object.keys(this.emptyData).forEach(key => {
        if (key == 'number') {
          newRow[key] = 1;
        } else if(key == 'sort') {
          newRow[key] = selectedMaterial.type || '';
        } else if(key === 'snList') {
          newRow[key] = selectedMaterial.snList || [];
        } else if(key === 'salePrice') {
          newRow[key] = selectedMaterial.salePrice || 0
        } else {
          newRow[key] = selectedMaterial[key];
        }
      })
      
      let newData = this.data.slice();
      newData[index] = newRow
      this.$emit('input', newData)
    },
    hasRow(value) {
      return this.data.some(item => item.id === value);
    },
    /**
    * @description 修改物料预计用量
    */
    handleSparepartNum(item) {
      let value = Number(item.number);
      let count = MathUtil.decimalNumber(value);
      let max = item.repertoryCount || PART_SERVICE_LIST_PRENUM_MAX_LENGTH;
      let min = max ? (max > 1 ? 1 : max) : 1;

      if (value <= 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.rightNumTip'));
        item.number = min;
        return;
      }

      if (value > max) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.applyNumMax', {max}));
        item.number = max;
        return;
      }
      
      if (count != -1 && count == 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.greaterThanZeroTip1'));
        item.number = min;
        return;
      }
      
      if (count != -1 && count != 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.greaterThanZeroTip2', {count}));
        item.number = min;
      }
    },
    /**
    * @description 预计用量小数位
    */
    decimalNumber(num) {
      let { sparepart2, precision } = this.partConfig;
      let count = MathUtil.decimalNumber(num);

      if(!sparepart2 && count != 0) return 0;
      if(precision >= count) return -1;
      return precision;
    },
    /**
    * @description 选择仓库
    */
    chooseRepertory(value, row) {
      row.repertoryId = value.repertoryId;
      row.repertoryCount = value.repertoryCount;
    },
    outsideGetTableData() {
      return this.data || []
    },
    outsideSetTableData() {
      this.multipleSelection = [];
      this.$refs?.materialTable?.clearSelection();
    },
    handleSelectionChange(value) {
      this.multipleSelection = value
    }
  },
  components: {
    [SearchMaterialSelect.name]: SearchMaterialSelect,
    [MaterialSnDialog.name]: MaterialSnDialog
  }
}
</script>

<style lang="scss">
  .search-in-part-item {
    padding: 8px 5px 8px 0;
    overflow: hidden;
    max-width: 260px;
    p {
      /*@include text-ellipsis();*/
      line-height: 20px;
      margin: 0 16px 0 0;
      // color: $text-color-primary;
      white-space: initial;
      span {
        // color: $text-color-regular;
      }
    }

    .no_empty {
      padding: 0;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
  }
</style>

<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}

.el-table {
  &::before {
    content: "";
  }
}
</style>